//
//  ILGWeakTimer.m
//  ILGDemo
//
//  Created by zhangtongle on 2017/5/11.
//  Copyright © 2017年 Happy. All rights reserved.
//

#import "ILGWeakTimer.h"

@interface ILGWeakTimer ()
@property (nonatomic, weak) _Nullable id target;
@property (nonatomic, assign) _Nullable SEL selector;
@end

@implementation ILGWeakTimer

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)timeInterval
                                     target:(nonnull id)aTarget
                                   selector:(nonnull SEL)aSelector
                                   userInfo:(nullable id)userInfo
                                    repeats:(BOOL)repeats  {
    ILGWeakTimer *weakTimerTarget = [[ILGWeakTimer alloc] init];
    weakTimerTarget.target = aTarget;
    weakTimerTarget.selector = aSelector;
    
    NSTimer  *timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:weakTimerTarget selector:@selector(p_timerEvent:) userInfo:userInfo repeats:repeats];
    
    return timer;
}

+ (NSTimer * _Nullable)scheduledTimerWithTimeInterval:(NSTimeInterval)timeInterval target:(nonnull id)aTarget block:(_Nonnull ILGWeakTimerBlock)block userInfo:(nullable id)userInfo repeats:(BOOL)repeats {
    ILGWeakTimer *weakTimerTarget = [[ILGWeakTimer alloc] init];
    weakTimerTarget.target = aTarget;
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:weakTimerTarget selector:@selector(p_timerBlock:) userInfo:userInfo ? @[[block copy], userInfo]:@[[block copy]] repeats:repeats];
    
    return timer;
}


#pragma mark Private method

- (void)p_timerEvent:(NSTimer *)timer {
    if (self.target) {
        [self.target performSelector:self.selector withObject:timer.userInfo afterDelay:0];
        
    } else {
        [timer invalidate];
    }
}

- (void)p_timerBlock:(NSTimer *)timer {
    NSArray *infoArr = timer.userInfo;
    ILGWeakTimerBlock block = infoArr[0];
    
    if (self.target) {
        block ? block(infoArr.count > 1 ? infoArr[1]:nil):nil;
    } else {
        [timer invalidate];
    }
}

@end
